/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.left = (left === undefined ? null : left)
        this.right = (right === undefined ? null : right)
    }
}

function zigzagLevelOrder(root: TreeNode | null): number[][] {
    const resArr : number[][] = [];
    if (root == null)
        return resArr;
    let queue : TreeNode[] = [];
    queue.push(root!);
    let reverse_flag = false;
    while(queue.length > 0)
    {
        const new_queue : (TreeNode| null)[] = [];
        const cur_layer_vals = queue.map((node) => node.val);
        reverse_flag && cur_layer_vals.reverse();
        reverse_flag = !reverse_flag;
        resArr.push(cur_layer_vals);
        queue.forEach((node) => {
            new_queue.push(node.left);
            new_queue.push(node.right);
        });
        queue = new_queue.filter((node) => (node!=null)) as TreeNode[];
    }
    return resArr;
};